package com.classtest.classtestdemo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.classtest.classtestdemo.bean.ImageTest;
import com.classtest.classtestdemo.mapper.ImageTestMapper;
import com.classtest.classtestdemo.service.ImageTestService;
import com.classtest.classtestdemo.utlis.PKGeneration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileOutputStream;

@Service
public class ImageTestServiceImpl extends ServiceImpl<ImageTestMapper, ImageTest> implements ImageTestService {
    @Autowired
    ImageTestMapper imageTestMapper;
    @Override
    public void imageUpload(String json, MultipartFile file) throws Exception {
        ImageTest imageTest = JSONObject.parseObject(json, ImageTest.class);
        String imageName = imageTest.getId();
        imageTest.setImagePath("C:\\Users\\MingleHeart\\ImageBasisUp"+"\\"+imageName+".jpg");
        uploadFile(file.getBytes(), "C:\\Users\\MingleHeart\\ImageBasisUp", imageName+".jpg");
        imageTestMapper.imageUpload(imageTest);
    }
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}
